<!--应收设置-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves icon="el-icon-plus" :loading="downloadLoading" class="filter-item right-btn" type="primary" @click="toAdd">
        添加
      </el-button>
    </div>
    <ve-table
      :columns="columns"
      :table-data="tableData"
      row-key-field-name="id"
      :border-x="true"
      :border-y="true"
      :row-style-option="rowStyleOption"
      :checkbox-option="checkboxOptipon"
    />
    <div class="table-pagination">
      <ve-pagination
        :total="totalCount"
        :page-index="pageIndex"
        :page-size="pageSize"
        @on-page-number-change="pageNumberChange"
        @on-page-size-change="pageSizeChange"
      />
    </div>
    <el-dialog class="lnk-dialog"
               :close-on-click-modal="false"
               :title="dialogTitle"
               top="10vh"
               width="60%"
               :visible.sync="newDialog"
               :append-to-body="true" >
      <el-form ref="mainForm" :model="formData" :rules="rules"
               size="mini" class="editForm" label-width="80px">
        <!--表单项-->
        <el-row>
          <el-col  :span="8">
            <el-form-item label="名称" prop="name" class="car-form-item" >
              <el-input class="car-modal-col" v-model="formData.name" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="车辆类型" prop="carType" class="car-form-item">
              <el-select v-model="formData.carType" placeholder="请选择" clearable  class="car-modal-col" style="width: 100%">
                <el-option v-for="item in carTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="合作机构" prop="partnerType" class="car-form-item">
             <el-select v-model="partnerType" placeholder="请选择" clearable  class="car-modal-col" style="width:50%;" @change="getPartner">
               <el-option v-for="item in partnerTypes" :key="item.value" :label="item.label" :value="item.value" />
             </el-select>
             <el-select v-model="formData.partnerId" placeholder="请选择" clearable  class="car-modal-col" style="width:50%;">
               <el-option v-for="item in partners" :key="item.id" :label="item.name" :value="item.id" />
             </el-select>
            </el-form-item>
            <el-form-item label="收款时机" prop="name" class="car-form-item">
              <el-select v-model="formData.paymentTimeType" placeholder="请选择" clearable  class="car-modal-col" style="width:50%;">
                <el-option v-for="item in paymentTimeTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
               <el-input class="car-modal-col" v-model="formData.paymentTime" placeholder="请输入" style="width:50%;"/>
            </el-form-item>
          </el-col>
          <el-col  :span="8">
            <el-form-item label="收款项目" prop="name" class="car-form-item" >
              <el-select v-model="formData.paymentId" placeholder="请选择" clearable  class="car-modal-col">
                <el-option v-for="item in payments" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="员工" prop="name" class="car-form-item">
              <el-cascader
                v-model="value"
                class="car-modal-col"
                :options="options"
                @change="handleChange"></el-cascader>
            </el-form-item>
            <el-form-item label="扣收" prop="deduction" class="car-form-item">
              <el-select v-model="formData.deduction" placeholder="请选择" clearable  class="car-modal-col">
                <el-option v-for="item in isApplys" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核人1" prop="name" class="car-form-item">
              <el-cascader
                v-model="value"
                class="car-modal-col"
                :options="options"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col  :span="8">
            <el-form-item label="贷款银行" prop="bankId" class="car-form-item">
              <el-select v-model="formData.bankId" placeholder="请选择" clearable  class="car-modal-col">
                <el-option v-for="item in banks" :key="item.id" :label="item.bankName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="经销商" prop="distributorId" class="car-form-item">
              <el-select v-model="formData.distributorId" placeholder="请选择" clearable  class="car-modal-col">
                <el-option v-for="item in distributors" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="收款账户" prop="accountBankId" class="car-form-item">
              <el-select v-model="formData.accountBankId" placeholder="请选择" clearable  class="car-modal-col">
                <el-option v-for="item in bankAccounts" :key="item.id" :label="item.accountName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核人2" prop="nickName" class="car-form-item">
              <el-cascader
                v-model="value"
                class="car-modal-col"
                :options="options"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="节点" prop="nickName" class="car-form-item">
              <el-checkbox-group v-model="checkNode">
                  <el-checkbox v-for="nodes in allNode" :label="nodes.value" :key="nodes.value">{{nodes.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态" prop="nickName" class="car-form-item">
              <el-radio v-model="formData.status" label="1">启用</el-radio>
              <el-radio v-model="formData.status" label="2">禁用</el-radio>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="newDialog = false;$refs['mainForm'].resetFields();" >取消</el-button>
        <el-button type="primary" @click="addData()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
  .table-pagination {
    margin-top: 20px;
    text-align: right;
  }
  .right-btn{
    float: right;
  }
  .dialog-footer{
    text-align: center;
  }
</style>

<script>

  export default {
    data() {
      return {
        tableData: [],
        editorFlag: false,
        dialogTitle: '新增应收设置',
        rules: {
          name: [
            {required: true, trigger: 'blur'}
          ],
          date1: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ]
        }, // 表单校验规则
        value: [],
        appId:'',
        dataTable: [],
        totalCount: '',
        options: [{
          value: 'zhinan',
          label: '指南',
          children: [{
            value: 'shejiyuanze',
            label: '设计原则',
            children: [{
              value: 'yizhi',
              label: '一致'
            }, {
              value: 'fankui',
              label: '反馈'
            }, {
              value: 'xiaolv',
              label: '效率'
            }, {
              value: 'kekong',
              label: '可控'
            }]
          },
          ]
        }],
        newDialog: false, // 添加弹框
        formData: {},     // 添加表单
        // page index
        pageIndex: 1,
        // page size
        pageSize: 10,

        partnerType:'',
        carTypes:[{value:0,label:'新车'},{value:1,label:'二手车'}],
        isApplys:[{value:0,label:'是'},{value:1,label:'否'}],
        partnerTypes:[{value:0,label:'GPS'},{value:1,label:'抵押机构'},{value:2,label:'挂牌机构'}],
        partners:[],
        paymentTimeTypes:[{value:0,label:'即刻'},{value:1,label:'日结'},{value:2,label:'周结'},{value:3,label:'月结'},{value:4,label:'季结'}],
        banks:[],
        payments:[],
        bankAccounts:[],
        distributors:[],

        allNode:[{value:0,label:'风控已审核'},{value:1,label:'公司已垫款'},{value:2,label:'银行已放款'},{value:3,label:'已抵押'},{value:4,label:'GPS录入'},
        {value:5,label:'初审'},{value:6,label:'签约已确认'},{value:7,label:'待结清'}],

        checkNode:[],

        listQuery: {},
        rowStyleOption: { // 表格样式
          stripe: true, // 斑马纹
          hoverHighlight: true, // hover高亮
          clickHighlight: true // 点击行高亮
        },
        checkboxOptipon: {
          // 行选择改变事件
          selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
            console.log(row, isSelected, selectedRowKeys)
          },
          // 全选改变事件
          selectedAllChange: ({ isSelected, selectedRowKeys }) => {
            console.log(isSelected, selectedRowKeys)
          }
        },
        columns: [
          {
            field: '',
            key: 'f',
            // type=checkbox
            type: 'checkbox',
            title: '',
            width: 50,
            align: 'center'
          },
          {
            field: 'name',
            key: 'a',
            title: '名称',
            align: 'center'
          },
          { field: 'paymentId', key: 'b', title: '收款项目', align: 'center' },
          { field: 'bankId', key: 'c', title: '贷款银行', align: 'center' },
          { field: 'address', key: 'e', title: '期数', align: 'center'},
          { field: 'address', key: 'f', title: '扣收', align: 'center',
            renderBodyCell: ({row, column, rowIndex}, h) => {
              // 在这里写转换方法
              return (
              <span>
              {row.isApply === 1?'否':'是'}
            </span>
            )
            }},
          { field: 'status', key: 'g', title: '状态', align: 'center',
            renderBodyCell: ({row, column, rowIndex}, h) => {
              // 在这里写转换方法
              return (
              <span>
              {row.status === 1?<el-tag type={'success'}>启用</el-tag>:<el-tag type={'danger'}>禁用</el-tag>}
            </span>
            )
            }},
          { field: 'hobby', key: 'h', title: '操作',width: '300px',
            align: 'center',
            renderBodyCell: ({ row, column, rowIndex }, h) => {
              return (
              <span>
                 <el-button circle icon="el-icon-edit" className="filter-item" type={'primary'}
                            on-click={() => this.editorDealer(row)}
                 ></el-button>
                {row.status === 1 ? <el-button circle icon="el-icon-remove" className="filter-item" type={'info'}
                                               on-click={() => this.forbidorDealer(row)}
                  ></el-button>
                  : <el-button circle icon="el-icon-success" className="filter-item" type={'success'}
                               on-click={() => this.forbidorDealer(row)}
                  ></el-button>
                }
                <el-button circle icon="el-icon-delete" className="filter-item" type={'danger'}
                           on-click={() => this.deleteorDealer(row)}
                ></el-button></span>
            )
            }
          }
        ]
      }
    },
    computed: {
    },
    created() {
      this.appId = sessionStorage.getItem("appId");
      this.getBank();
      this.getPayment();
      this.getBankAccount();
      this.getDistributor();
      this.initDatabase();
    },
    methods: {
      // page number change
      pageNumberChange(pageIndex) {
        this.pageIndex = pageIndex
        this.initDatabase();
      },

      // page size change
      pageSizeChange(pageSize) {
        this.pageIndex = 1;
        this.pageSize = pageSize;
        this.initDatabase();
      },

      /**
        * 初始化数据
        * @date 2021-05-10
        */
       async getBank() {
          let param = {appId: await sessionStorage.getItem("appId")};
          let data = await this.$http.post('/auth/bankSetup/listAll', param);
          if (data.code === 200) {
            this.banks = data.data;
          }
       },

      /**
        * 初始化数据
        * @date 2021-05-10
        */
       async getPayment() {
          let param = {appId: await sessionStorage.getItem("appId"),paymentType:1};
          let data = await this.$http.post('/auth/paymentName/listAll', param);
          if (data.code === 200) {
            this.payments = data.data;
          }
       },

      /**
        * 初始化数据
        * @date 2021-05-10
        */
       async getPartner() {
          let param = {appId: await sessionStorage.getItem("appId"),partnerType:this.partnerType};
          let data = await this.$http.post('/auth/partners/listAll', param);
          if (data.code === 200) {
            this.partners = data.data;
          }
       },

      /**
        * 初始化数据
        * @date 2021-05-10
        */
       async getPartnerDetail(id) {
          let data = await this.$http.get('/auth/partners/detail/'+id, {});
          if (data.code === 200 && data.data) {
            this.partnerType = data.data.partnerType;
            this.getPartner();
          }
       },

       /**
         * 初始化数据
         * @date 2021-05-10
         */
        async getDistributor() {
           let param = {appId: await sessionStorage.getItem("appId")};
           let data = await this.$http.post('/auth/distributor/listAll', param);
           if (data.code === 200) {
             this.distributors = data.data;
           }
        },

       /**
         * 初始化数据
         * @date 2021-05-10
         */
        async getBankAccount() {
           let param = {appId: await sessionStorage.getItem("appId"),accountType:1};
           let data = await this.$http.post('/auth/bankAccount/listAll', param);
           if (data.code === 200) {
             this.bankAccounts = data.data;
           }
        },


      /**
       * 初始化数据
       * @date 2021-05-10
       */
      async initDatabase() {
        this.tableData = [];
        let param = {appId: await sessionStorage.getItem("appId")};
        let data = await this.$http.post('/auth/receivableSetting/list/' + this.pageIndex + "/" + this.pageSize, param);
        console.log(data);
        if (data.code === 200) {
          this.tableData = data.data;
          this.totalCount = data.total;
        } else {
          this.$message({
            type: 'error',
            message: '查询失败，请刷新页面'
          });
        }
        console.log(this.tableData)
      },
      /**
       * 禁用
       * @param {Object} row
       */
      async forbidorDealer(row) {
        let that = this
        this.$alert('是否确认禁用', '确认禁用', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            that.formData = row;
            if (row.status === 1) {
              that.formData.status = 0;
            } else {
              that.formData.status = 1;
            }
            let data = await that.$http.post('/auth/receivableSetting/update', that.formData)
            console.log(data);
            if (data.code === 200) {
              that.initDatabase();
            } else {
              that.$message({
                type: 'error',
                message: '操作失败'
              });
            }
          }).catch(() => {
          that.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },

      /**
       * 删除
       * @param {Object} row
       */
      async deleteorDealer(row) {

        let that = this

        this.$alert('是否确认删除', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = await that.$http.delete('/auth/distributor/delete/' + row.id, {})
          console.log(data);
          if (data.code === 200) {
            that.initDatabase();
          } else {
            that.$message({
              type: 'info',
              message: '操作失败，请重试'
            });
          }
        })
      },

      /**
       * 编辑
       * @date 2021-05-08
       * @param row
       */
      editorDealer(row) {
        this.formData = row;
        this.checkNode = [];
        if(this.formData.node != "" && this.formData.node != undefined && this.formData.node != null) {
          let checkNode = this.formData.node.split(",");
          for(var i = 0;i<checkNode.length;i++) {
            this.checkNode.push(parseInt(checkNode[i]))
          }
        }
         this.getPartnerDetail(row.partnerId);
        this.newDialog = true
        this.editorFlag = true // 编辑标识
        this.dialogTitle = '编辑应收设置'
      },
      /**
       * 点击新增按钮
       * @date 2021-05-08
       */
      toAdd(data) {
        this.formData = {}
        this.newDialog = true
        this.editorFlag = false  // 编辑标志
        this.dialogTitle = '新增应收设置'
      },
      /**
       * 新增操作
       * @date 2021-05-08
       */
      async addData() {
        this.$refs['mainForm'].validate(async (valid) => {
          if (valid) {
            if(this.checkNode.length > 0) {
              let node = "";
              for(var i = 0;i<this.checkNode.length;i++) {
                 node = node + this.checkNode[i] + ",";
              }
               this.formData.node = node.substring(0,node.length-1);
            }


            if (this.formData.id) {
              let data = await this.$http.post('/auth/receivableSetting/update', this.formData)
              console.log(data);
              if (data.code === 200) {
                this.newDialog = false;
                this.initDatabase();
              } else {
                this.$message({
                  type: 'info',
                  message: '操作失败，请重试'
                });
              }
            } else {
              this.formData.appId = this.appId;
              let data = await this.$http.post('/auth/receivableSetting/save', this.formData)
              console.log(data);
              if (data.code === 200) {
                this.newDialog = false;
                this.initDatabase();
              } else {
                this.$message({
                  type: 'info',
                  message: '操作失败，请重试'
                });
              }
            }
          }
        })
      }
    }
  }
</script>
